package com.leaf.spring.y201906.day25.arithmetic.random;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.leaf.spring.y201906.day25.arithmetic.ServerIps;

/**
 * 随机+权重算法实现负载均衡 <br/>
 * 根据权重添加server到新的集合中，权重是多少，则加入多少个server。 <br/>
 * 缺点：若权重很大，会增加内存负载
 * 
 * @Title:
 * @Description:
 * @Author: leaf
 * @Since:2019年6月25日
 * @Version:1.1.0
 */
public class WeightRandomArith {

	public String getServer() {

		// 服务
		List<String> servers = new ArrayList<>();

		for (String server : ServerIps.WEIGHT_LIST.keySet()) {

			int weight = ServerIps.WEIGHT_LIST.get(server);

			// 按照权重添加服务
			for (int i = 0; i < weight; i++) {
				servers.add(server);
			}

		}

		Random random = new Random();
		int pos = random.nextInt(servers.size());

		return servers.get(pos);
	}

	public static void main(String[] args) {

		WeightRandomArith arith = new WeightRandomArith();

		for (int i = 0; i < 20; i++) {
			System.out.println(arith.getServer());
		}

	}

}
